package com.fiveGroup.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fiveGroup.pojo.UserFavoriteProduct;
import com.fiveGroup.pojo.UserFollowSeller;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.pojo.vo.ProductFavoriteVo;
import com.fiveGroup.service.UserFavoriteProductService;
import com.fiveGroup.service.UserFollowSellerService;
import com.fiveGroup.util.UserContextHolder;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

// 收藏加关注
@RestController
@RequestMapping("/api/FollowAndFavorite")
@Slf4j
@RequiredArgsConstructor
public class FollowAndFavoriteController {

    private final UserFavoriteProductService userFavoriteProductService;
    private final UserFollowSellerService userFollowSellerService;

    @GetMapping("/getUserFavoriteProducts")
    public DataVo getUserFavoriteProducts(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 1. 校验用户登录状态
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录");
        }

        // 2. 分页查询（调用Mapper的selectUserFavoritesWithProduct方法）
        IPage<ProductFavoriteVo> iPage = new Page<>(currentPage, pageSize);

        QueryWrapper<UserFavoriteProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<ProductFavoriteVo> resultPage = userFavoriteProductService.getFavorite(iPage, queryWrapper);

        iPage.setRecords(resultPage);

        // 3. 返回分页结果（含records和total，前端直接解析）
        return DataVo.success(iPage);
    }

    // 增加收藏(前端点击收藏)
    @PostMapping("/addFavorite")
    public DataVo addFavorite(@RequestBody @Valid UserFavoriteProduct favoriteProduct) {

        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录，请登录");
        }

        if (favoriteProduct.getProductId() == null) {
            return DataVo.fail("商品id不能为空");
        }

        // 创建收藏实体类
        UserFavoriteProduct userFavoriteProduct = new UserFavoriteProduct();
        userFavoriteProduct.setUserId(userId);
        userFavoriteProduct.setProductId(favoriteProduct.getProductId());
        userFavoriteProduct.setCreatedAt(LocalDate.now());

        // 添加至表中
        boolean isSave = userFavoriteProductService.save(userFavoriteProduct);

        // 添加玩判断是否添加成功
        if (!isSave) {
            return DataVo.fail("收藏失败");
        }
        return DataVo.success("收藏成功");
    }

    // 删除收藏(前端取消收藏)
    @PostMapping("/deleteFavorite")
    public DataVo deleteFavorite(@RequestBody @Valid @Size(min = 1, message = "id不能为空") ArrayList<Long> ids) {

        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录");
        }
        // 根据用户ID和商品ID删除
        QueryWrapper<UserFavoriteProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .in("product_id", ids);

        boolean isDelete = userFavoriteProductService.remove(queryWrapper);
        return isDelete ? DataVo.success("删除成功") : DataVo.fail("删除失败");
    }

    // 增加关注
    @PostMapping("/addFollow")
    public DataVo addFollow(@RequestBody @Valid UserFollowSeller followSeller) {

        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录，请登录");
        }

        // 判断商家是否为空
        if (followSeller.getSellerId() == null) {
            return DataVo.fail("卖家id不能为空");
        }

        // 检查是否已关注
        QueryWrapper<UserFollowSeller> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("seller_id", followSeller.getSellerId());
        if (userFollowSellerService.exists(queryWrapper)) {
            return DataVo.fail("已关注该卖家");
        }

        // 创建关注实体类
        UserFollowSeller userFollowSeller = new UserFollowSeller();
        userFollowSeller.setUserId(userId);  // 使用当前登录用户ID
        userFollowSeller.setSellerId(followSeller.getSellerId());
        userFollowSeller.setCreatedAt(LocalDate.now());

        // 调用方法
        boolean isSave = userFollowSellerService.save(userFollowSeller);

        return isSave ? DataVo.success("关注成功") : DataVo.fail("关注失败");
    }

    // 取消关注
    @PostMapping("/deleteFollow")
    public DataVo deleteFollow(@RequestBody @Size(min = 1, message = "id不能为空") ArrayList<Long> sellerIds) {
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录，请登录");
        }

        // 确保取消的是当前用户的关注
        QueryWrapper<UserFollowSeller> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("seller_id", sellerIds)
                .eq("user_id", userId);

        boolean isDelete = userFollowSellerService.remove(queryWrapper);

        return isDelete ? DataVo.success("取消成功") : DataVo.fail("取消失败");
    }

    // 检查商品是否被当前用户收藏
    @GetMapping("/checkFavorite")
    public DataVo checkFavorite(@RequestParam Long productId) {
        if (productId == null) {
            return DataVo.fail("商品id不能为空");
        }

        // 获取当前上下文用户id
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录");
        }

        // 查询用户是否收藏了该商品
        QueryWrapper<UserFavoriteProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("product_id", productId);  // 补充查询条件

        boolean isFavorited = userFavoriteProductService.exists(queryWrapper);
        return DataVo.success(isFavorited);
    }

    // 检查关注状态的接口
    @GetMapping("/checkFollow")
    public DataVo checkFollow(@RequestParam Long sellerId) {
        if (sellerId == null) {
            return DataVo.fail("卖家id不能为空");
        }

        // 获取当前登录用户ID
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录");
        }

        // 查询当前用户是否关注了该卖家
        QueryWrapper<UserFollowSeller> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)  // 关联当前用户
                .eq("seller_id", sellerId);  // 关联目标卖家

        boolean isFollowed = userFollowSellerService.exists(queryWrapper);
        return DataVo.success(isFollowed);
    }

    // 添加获取收藏数量的接口
    @GetMapping("/getFavoriteCount") // 接口路径与前端调用一致
    public DataVo getFavoriteCount(@RequestParam(required = false) Long productId) {
        try {
            // 获取当前用户ID（如果需要查询用户的收藏数量）
            Long userId = UserContextHolder.getUserId();
            if (userId == null) {
                return DataVo.fail("用户未登录");
            }
            // 调用服务层方法获取收藏数量（根据业务需求实现）
            int count = userFavoriteProductService.getFavoriteCount(userId, productId);
            return DataVo.success(count);
        } catch (Exception e) {
            return DataVo.fail("获取收藏数量失败：" + e.getMessage());
        }
    }
}
